package com.ch4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author woldier
 * @version 1.0
 * @description 多把锁
 * @date 2023/5/8 9:17
 **/
public class Demo10 {

    public static void main(String[] args) {
//        Room1 room = new Room1();
        Room2 room = new Room2();
        new Thread(room::work,"工作线程").start();
        new Thread(room::sleep,"休息线程").start();

    }

}

/**
 * 公用同一把锁的情况
 */
@Slf4j(topic = "c.Thread")
final class  Room1{
    public synchronized void sleep(){
        log.debug("sleeping..........");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    public synchronized void work(){
        log.debug("working..........");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}



/**
 * 分锁
 */
@Slf4j(topic = "c.Thread")
final class Room2{
    private final Object sleepRoom = new Object();
    private final Object workRoom = new Object();
    public  void sleep(){
        synchronized (sleepRoom){
            log.debug("sleeping..........");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public  void work(){
        synchronized (workRoom){
            log.debug("working..........");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}




